package NewCode;

import java.util.*;

/**
 * @author wangchenghao
 * @date 2021/7/22
 **/
public class NC37 {


    public class Interval {
        int start;
        int end;

        Interval() {
            start = 0;
            end = 0;
        }

        Interval(int s, int e) {
            start = s;
            end = e;
        }
    }

    public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
        if (intervals.size() == 0) {
            return new ArrayList<Interval>();
        }
        intervals.sort(new Comparator<Interval>() {
            @Override
            public int compare(Interval o1, Interval o2) {
                return o1.start - o2.start;
            }
        });
        ArrayList<Interval> merged = new ArrayList<>();
        for (int i = 0; i < intervals.size(); ++i) {
            int L = intervals.get(i).start, R = intervals.get(i).end;
            //如果当前区间的左端点在数组 merged 中最后一个区间的右端点之后，那么它们不会重合，我们可以直接将这个区间加入数组 merged 的末尾；
            if (merged.size() == 0 || merged.get(merged.size() - 1).end < L) {
                merged.add(new Interval(L, R));
            } else {
                //否则，它们重合，我们需要用当前区间的右端点更新数组 merged 中最后一个区间的右端点，将其置为二者的较大值
                merged.get(merged.size() - 1).end = Math.max(merged.get(merged.size() - 1).end, R);
            }
        }
        return merged;

    }
}
